<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="showDialog = true"
        >添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <!-- 根据row.isEdit是否存在使用v-if和v-else来进行编辑模式的切换 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? "启用" : "禁用" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="editSubmit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <!-- 权限按钮 -->
              <el-button size="mini" type="text" @click="authorityJurisdiction(row.id)">分配权限</el-button>
              <!-- 编辑按钮 -->
              <el-button size="mini" type="text" @click="editRole(row)">编辑</el-button>
              <!-- 删除按钮 -->
              <el-popconfirm title="这是一段内容确定删除吗?" @onConfirm="delRole(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <!-- 分页组件属性赋值 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 添加角色弹层 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="form" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- Switch 开关： :active-value="1" :inactive-value="0" 开启为1 关闭为0 -->
          <el-switch
            v-model="roleForm.state"
            size="mini"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="primary"
                size="mini"
                @click="onSubmit"
              >确定</el-button>
              <el-button
                size="mini"
                @click="showDialog = false"
              >取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限弹出层 -->
    <!-- 树形组件不能使用v-model 所以用elm属性绑定ref="pmTree" -->
    <el-dialog :visible.sync="jurisdictionVisible" title="分配权限" width="700px">
      <el-tree ref="pmTree" check-strictly node-key="id" :default-checked-keys="PermissionIdList" default-expand-all show-checkbox :data="PermissionList" :props="{label:'name'}" />
      <template #footer>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="mini" @click="onRoleJurisdiction">确定</el-button>
          <el-button size="mini" @click="jurisdictionVisible=false">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleAPI, allotRoleJurisdictionAPI, delRoleAPI, editRoleAPI, getOddRoleAPI, getRoleListAPI } from '@/api/role'
import { getPermissionListAPI } from '@/api/permission'
import { list2Tree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      // 权限列表id
      PermissionIdList: [],
      // 权限列表
      PermissionList: [],
      // 分配权限弹出层的显示隐藏
      jurisdictionVisible: false,
      // 定义一个变量控制弹层显示隐藏
      showDialog: false,
      // 定义一个空数组（用来赋值角色的详情）
      list: [],
      pageParams: {
        // 第几页
        page: 1,
        // 一页多少个数据
        pagesize: 5,
        // 总数量
        total: 0
      },
      // 定义弹层收集表单数据（双向绑定）
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      // 校验规则
      rules: {
        // 名称
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        // 描述
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  // 侦听器
  watch: {
    // 弹层关闭时重置表单数据
    showDialog(newValue, oldValue) {
      if (!newValue) {
        this.$refs.form.resetFields()
      }
    }
  },
  // 最先发请求获取数据
  created() {
    // 调用获取角色列表方法
    this.getRoleList()
  },

  methods: {
    // 分配权限按钮
    async  authorityJurisdiction(id) {
      this.id = id
      const { permIds } = await getOddRoleAPI(id)
      this.PermissionIdList = permIds
      this.PermissionList = list2Tree(await getPermissionListAPI(), 0)
      this.jurisdictionVisible = true
    },
    // 分配权限弹层的确认按钮
    // 树形组件不能使用v-model 需要用this.$refs.pmTree.getCheckedKeys()的elm属性拿最新id
    async onRoleJurisdiction() {
      await allotRoleJurisdictionAPI({ id: this.id, permIds: this.$refs.pmTree.getCheckedKeys() })
      this.jurisdictionVisible = false
      this.$message.success('分配权限成功')
    },
    // 添加角色弹层确认按钮
    async onSubmit() {
      // 确认表单校验
      await this.$refs.form.validate()
      // 调用API增加角色
      await addRoleAPI(this.roleForm)
      // 渲染页面
      this.getRoleList()
      // 关闭弹层
      this.showDialog = false
      // 提示用户
      this.$message.success('增加成功')
    },
    // 编辑按钮
    editRole(row) {
      row.isEdit = true
    },
    // 编辑模式确认按钮
    async editSubmit(row) {
      // 判断角色名称和角色权限是否有值
      if (row.editRow.name && row.editRow.description) {
        // 调用编辑角色API
        await editRoleAPI({ ...row.editRow })
        // 用新的编辑内容和旧的内容合并更新
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        // 提示用户
        this.$message.success('编辑成功')
      } else {
        this.$message.warning('数据不能为空')
      }
    },
    // 删除按钮
    async delRole(id) {
      // 调用删除角色API
      await delRoleAPI(id)
      // 提示用户
      this.$message.success('删除成功')
      // 当前页面删除的角色只剩1个 分页向前一页
      this.list.length === 1 && this.pageParams.page--
      // 重新渲染
      this.getRoleList()
    },
    // 封装获取角色列表方法
    async getRoleList() {
      const { rows, total } = await getRoleListAPI(this.pageParams)
      // 赋值角色列表
      this.list = rows
      // 赋值总数量
      this.pageParams.total = total
      // 判断isEdit对象是否存在作为条件
      if (!this.roleForm.isEdit) {
        // 遍历循环为每很数据加上isEdit和editRow的对象属性
        this.list.forEach(item => {
          this.$set(item, 'isEdit', false)
          this.$set(item, 'editRow', {
            name: item.name,
            state: item.state,
            description: item.description,
            id: item.id
          })
        })
      }
    },
    // 监听分页变动 刷新数据
    async changePage(page) {
      this.pageParams.page = page
      await this.getRoleList()
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
